cd /data
use tomerge_location_variables, clear
destring first_county first_zip first_tract, replace force
gen missing = first_state == . | first_county == . | first_tract == .
	forvalues x = 18/32{
		destring county_`x' zip_`x' tract_`x', replace force
		replace first_zip = zip_`x' if first_zip==.
		replace first_state = state_`x' if missing == 1
		replace first_county = county_`x' if missing == 1
		replace first_tract = tract_`x' if missing == 1
		replace first_age = `x' if missing == 1 & first_state != . & first_county != . & first_tract != .
		replace missing = 0 if first_state != . & first_county != . & first_tract != .
	}
replace first_state = . if missing == 1
replace first_county = . if missing == 1
replace first_tract = . if missing == 1
gen double locate = first_tract*100 + first_county*1000000 + first_state*1000000000
keep pid locate first_age
sort locate
save tomerge_location_variables2, replace

clear
use locate medinc msain9 using /data/hm00_action1
collapse (p50) medinc msain9, by(locate)
rename medinc tract_inc_90
rename msain9 msa_inc_90
destring locate, replace force
sort locate
merge 1:m locate using tomerge_location_variables2
drop if _merge == 1
drop _merge
sort locate
save tomerge_location_variables2, replace

clear
use locate medinc msain9 using /data/hm05_action1
collapse (p50) medinc msain9, by(locate)
rename medinc tract_inc_00
rename msain9 msa_inc_00
destring locate, replace force
sort locate
merge 1:m locate using tomerge_location_variables2
drop if _merge == 1
drop _merge
sort locate
save tomerge_location_variables2, replace
